package com.promote.algorithm;

/**
 * @ClassName LongestCommonPrefix
 * Description 最长的公共前缀
 * @Author LiZiHao
 * Date 2022/3/16 11:01
 * @Version 1.0
 **/
public class LongestCommonPrefix {

    public static String longestCommonPrefix(String[] strs) {

        //边界条件判断
        if (strs == null || strs.length == 0) {
            return "";
        }

        //默认第一个字符串是他们的公共前缀
        int i = 1;
        String per = strs[0];

        while (i < strs.length ) {
            //不断截取
            while (strs[i].indexOf(per) != 0) {
                per = per.substring(0, per.length() - 1);
            }
            i++;
        }
        return per;
    }

    public static void main(String[] args) {
        String[] strs = new String[]{"flower","flow","flight"};
        String res = longestCommonPrefix(strs);
        System.out.println(res);
    }
}
